use std::{env, process::exit};
use std::fs::File;
use reqwest;
use std::io::{self};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = env::args().skip(1).collect();
    if args.len() < 2 {
        println!("usage: webget [url] [output_file_name]");
        exit(-1);
    }
    let url = &args[0];
    let output = &args[1];

    // 发送GET请求
    let response = reqwest::get(url).await?;

    // 确保响应状态码是200（成功）
    if !response.status().is_success() {
        return Err(format!("Failed to download file: {}", response.status()).into());
    }

    // 创建或打开一个本地文件用于写入
    let mut dest_file = File::create(output)?;

    // 将响应体内容写入到文件中
    let bytes = response.bytes().await?;

    io::copy(&mut bytes.as_ref(), &mut dest_file)?;

    Ok(())
}